package com.foolishbird.sdk.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.foolishbird.sdk.api.FBSDK;
import com.foolishbird.sdk.params.bean.ConfigInfo;
import com.foolishbird.sdk.ui.assist.OnFinishActivityListener;
import com.foolishbird.sdk.ui.view.DialogFactory;
import com.foolishbird.sdk.utils.WL;
import com.foolishbird.sdk.utils.XmlUtils;


public class FoolishBirdLoginRegisterFragment extends BaseDialogFragment implements View.OnClickListener, TextWatcher, CompoundButton.OnCheckedChangeListener {

    private static final String TAG = FoolishBirdLoginRegisterFragment.class.getSimpleName();

    private static final String DEFAULT_LINK_URL = "https://www.baidu.com";

    private EditText mRegisterUserAccountEt;
    private EditText mRegisterUserPasswordEt;
//    private SwitchView mSwitchView;
    private Button mRegisterSubmitBtn;
    private ImageView mCloseWindowBth;
    private CheckBox mUserProtocolBox;
    private View mUserProtocolBtn,mConverBtn;


    public static final FoolishBirdLoginRegisterFragment newInstance() {
        FoolishBirdLoginRegisterFragment fragment = new FoolishBirdLoginRegisterFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View contentView = doInflateContentView(inflater, container, getLayoutIdentifier("foolishbird_dialog_login_regist"));
        mRegisterUserAccountEt = contentView.findViewById(getViewIdentifier("fb_fragment_regsit_username_edit"));
        mRegisterUserPasswordEt = contentView.findViewById(getViewIdentifier("fb_fragment_regsit_password_edit"));
//        mSwitchView = contentView.findViewById(getViewIdentifier("activity_register_password_switch"));
        mRegisterSubmitBtn = contentView.findViewById(getViewIdentifier("fb_fragment_regist_login_btn"));
        mCloseWindowBth = contentView.findViewById(getViewIdentifier("fb_fragment_login_back"));
        mUserProtocolBox = contentView.findViewById(getViewIdentifier("fb_fragment_login_checkbox"));
        mRegisterUserPasswordEt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        mUserProtocolBtn = contentView.findViewById(getViewIdentifier("fb_fragment_login_user_protocol"));

         if(XmlUtils.isNeedPrivate()){
             mUserProtocolBox.setChecked(false);
         }else{
             mUserProtocolBox.setChecked(true);
         }
//        mSwitchView.setOnClickListener(this);
        mCloseWindowBth.setOnClickListener(this);
        mRegisterSubmitBtn.setOnClickListener(this);
        mUserProtocolBtn.setOnClickListener(this);
        try {
            mConverBtn = contentView.findViewById(getViewIdentifier("fb_fragment_login_user_yinsi"));
            mConverBtn.setOnClickListener(this);
        }catch (Exception e){
            e.printStackTrace();
        }

        mRegisterUserAccountEt.addTextChangedListener(this);
        mRegisterUserPasswordEt.addTextChangedListener(this);
        mUserProtocolBox.setOnCheckedChangeListener(this);
        mRegisterUserPasswordEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if(actionId == EditorInfo.IME_ACTION_DONE&&mRegisterSubmitBtn.isEnabled()){
                    submitUserRegisterInfo();
                }
                Log.e("CodeEtOnKeyListener",actionId+".."+(event==null));
                return false;
            }
        });
        return contentView;
    }

    @Override
    public void onClick(View view) {
        if (view == mRegisterSubmitBtn) {
            if(mUserProtocolBox.isChecked()){
                submitUserRegisterInfo();
            }else{
                Toast.makeText(getActivity(),"请先阅读并同意协议",Toast.LENGTH_SHORT).show();
            }
        }
//        else if (view == mSwitchView) {
//            switchUserRegisterPasswordDisplayType();
//        }
        else if (view == mCloseWindowBth) {
            finishActivity();
        } else if (view == mUserProtocolBtn) {
            ConfigInfo configInfo = FBSDK.getInstance().getPlatformConfigInfo();
            String linkUrl = configInfo != null ? configInfo.getCommonLinks().getUserAgreement() : DEFAULT_LINK_URL;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(TextUtils.isEmpty(linkUrl) ? DEFAULT_LINK_URL : linkUrl)));
        }else if (view == mConverBtn){
            ConfigInfo configInfo = FBSDK.getInstance().getPlatformConfigInfo();
            String linkUrl = configInfo != null ? configInfo.getCommonLinks().getPrivacyAgreement(): DEFAULT_LINK_URL;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(TextUtils.isEmpty(linkUrl) ? DEFAULT_LINK_URL : linkUrl)));
        }
    }

    private void finishActivity() {
        OnQuickRegisterListener listener = getOnQuickRegisterListener();
        if (listener != null) {
            listener.doFinishActivity(this);
        }
    }

//    private void switchUserRegisterPasswordDisplayType() {
//        if (mSwitchView.isOpened()) {
//            mRegisterUserPasswordEt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
//        } else {
//            mRegisterUserPasswordEt.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
//        }
//    }

    private void submitUserRegisterInfo() {
        String registerAccount = mRegisterUserAccountEt.getText().toString().trim();
        String registerPassword = mRegisterUserPasswordEt.getText().toString().trim();
        if(!mUserProtocolBox.isChecked()){
            Toast.makeText(getActivity(),"请先阅读并同意协议",Toast.LENGTH_SHORT).show();
            return;
        }
        WL.d(TAG, "registerAccount: " + registerAccount + " registerPassword: " + registerPassword);

        if (TextUtils.isEmpty(registerAccount)) {
            DialogFactory.createConfirmDialog(getActivity(), getString(getStringIdentifier("hnssn_hint_account"))).show();
            return;
        }

        if (TextUtils.isEmpty(registerPassword)) {
            DialogFactory.createConfirmDialog(getActivity(), getString(getStringIdentifier("hnssn_hint_password"))).show();
            return;
        }

        if (registerPassword.contains(" ") || registerAccount.contains(" ")) {
            DialogFactory.createConfirmDialog(getActivity(), getString(getStringIdentifier("hnssn_hint_password_blank"))).show();
            return;
        }

        OnQuickRegisterListener listener = getOnQuickRegisterListener();
        if (listener != null) {
            listener.doQuickRegister(registerAccount, registerPassword);
        }

    }


    private OnQuickRegisterListener getOnQuickRegisterListener() {
        if (!isNullContext()) {
            Activity activity = getActivity();
            if (activity instanceof OnQuickRegisterListener) {
                return (OnQuickRegisterListener) activity;
            }
        }
        return null;
    }

    private void checkSumbitButtonState() {
        String registerAccount = mRegisterUserAccountEt.getText().toString().trim();
        String registerPassword = mRegisterUserPasswordEt.getText().toString().trim();
        if (TextUtils.isEmpty(registerAccount) || TextUtils.isEmpty(registerPassword) || !mUserProtocolBox.isChecked()) {
            mRegisterSubmitBtn.setEnabled(false);
        } else {
            mRegisterSubmitBtn.setEnabled(true);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        checkSumbitButtonState();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        checkSumbitButtonState();
    }

    public interface OnQuickRegisterListener extends OnFinishActivityListener {

        void doQuickRegister(String username, String password);

    }
}
